<template>
	<view>
		<van-cell title="手机号" :value="userinfo.tel"/>
		<van-cell title="姓名" :value="userinfo.name"/>
		<van-cell title="科室" :value="userinfo.zDept"/>
		<van-cell title="角色" :value="userinfo.zRoles"/>
		<van-cell title="工号" :value="userinfo.jobNumber"/>
		<!-- <van-cell title="验证码" :value="userinfo.vtfyCode"/> -->
		<!-- 
		<van-cell-group v-if="oper != 'needconfirm'" title="设置">
			<van-cell :key="item" title="订阅通知">
				<view style="display: flex;flex-flow: row;justify-content: flex-end;">
					<van-button :data-item="item" :color="primaryColor" size="mini" @click="subscribeMessage" plain>订阅</van-button>
				</view>
			</van-cell>
		</van-cell-group> -->
		
		<view style="margin-top: 50px;">
			<van-button type="warning" @click="logout" plain block >退出登录</van-button>
		</view>
		
		<view v-if="oper == 'needconfirm'" class="oper">
			<button type="primary" :plain="true" @click="submit" size="mini">{{'确认无误'}}</button>
		</view>
		
		<van-dialog id="van-dialog" />
	</view>
</template>

<script>
	import Toast from '@/wxcomponents/toast/toast'
	import Dialog from '@/wxcomponents/dialog/dialog'
	import utils from '@/common/utils.js'
	export default {
		data() {
			return {
				primaryColor: getApp().globalData.primaryColor,
				roleList: [],
				userinfo:{},
				token: '',
				deptNameTemp: '',
				oper: '',
				userId: ''
			};
		},
		async onLoad(options) {
			try{
				console.log("user detail options")
				console.log(options)
				this.oper = options.oper
				this.roleList = await this.getRoles()
				// const userinfoTemp = JSON.parse(decodeURIComponent(options.userinfo))
				// userinfoTemp.roleName = this.roleList.filter(o => userinfoTemp.roles.includes(o.value)).map(o => o.lable).join(',')
				if(this.oper == 'needconfirm'){
					// this.token = options.token
					this.userId = options.userId
				}else{
					this.token = uni.getStorageSync('userinfo').token
					this.userId = uni.getStorageSync('userinfo').userId
				}
				const userinfoTemp = await this.getUserDetail()
				userinfoTemp.zRoles = this.roleList.filter(o => userinfoTemp.roles.includes(o.value)).map(o => o.label).join(',')
				userinfoTemp.zDept = this.getDeptName(userinfoTemp.partment)
				this.userinfo = userinfoTemp
				// const userinfo = await this.getUserDetail()
			}catch(e){
				//TODO handle the exception
			}
		},
		methods:{
			logout(){
				uni.clearStorageSync()
				uni.reLaunch({
					url:'../login-main/login-main'
				})
			},
			async getRoles(){
				return await utils.req('/config/getRoles',{token:'1'})
			},
			getDeptName(obj){
				if(!obj)return
				this.deptNameTemp = `${obj.name}-${this.deptNameTemp}`
				if(obj.up){
					return this.getDeptName(obj.up)
				}else{
					return this.deptNameTemp.substring(0, this.deptNameTemp.lastIndexOf('-'))
				}
			},
			async submit(){
				try{
					await utils.req('/wxuser/confirmUserInfo', {userId: this.userId})
					Toast('确认成功，正在跳转...')
					uni.setStorageSync('userinfo', this.userinfo)
					uni.switchTab({
						url:'../index/index'
					})
				}catch(e){
					Toast(e.msg)
				}
			},
			async getUserDetail(){
				return await utils.req('/user/getUserDetail', {userId: this.userId})
			},
			subscribeMessage() {
				//需要订阅的消息模板，在微信公众平台手动配置获取模板ID
				let message = '1212'
				//如果总是拒绝（subscriptionsSetting，2.10.1库才支持）
				if (this.versionCompare('2.10.1')) {
					uni.getSetting({
						withSubscriptions: true, //是否同时获取用户订阅消息的订阅状态，默认不获取
						success: (res) => {
							console.log(res)
							if (res.subscriptionsSetting && res.subscriptionsSetting.itemSettings &&
								res.subscriptionsSetting.itemSettings[message] == "reject") {
								//打开设置去设置
								this.openConfirm('检测到您没打开推送权限，是否去设置打开？')
			
							} else {
								uni.requestSubscribeMessage({
									tmplIds: [message],
									success: (res) => {
										if (res[message] == 'accept') {
											//用户允许
										}
									},
									fail: (res) => {
										console.info(res)
									},
								})
							}
						}
					})
				} else if (this.versionCompare('2.4.4')) {
					uni.requestSubscribeMessage({
						tmplIds: [message],
						success: (res) => {
							if (res[message] == 'accept') {
								//用户允许
							}
						},
						fail: (res) => {
							console.info(res)
						},
					})
				}
			},
			openConfirm(message) {
				Dialog.confirm({
					title: '提示',
					message: '检测到您没打开推送权限，是否去设置打开？'
				}).then(async () => {
					uni.openSetting({
						success: (res) => {
							console.log(res.authSetting)
						},
						fail: (error) => {
							console.log(error)
						}
					})
				}).catch(() => {
					// on cancel
				});
			},
			//基础库版本比较
			versionCompare(v) {
				const version = uni.getSystemInfoSync().SDKVersion
				if (this.compareVersion(version, v) >= 0) {
					return true
				} else {
					return false
				}
			},
			compareVersion(v1, v2) {
				v1 = v1.split('.')
				v2 = v2.split('.')
				const len = Math.max(v1.length, v2.length)
			
				while (v1.length < len) {
					v1.push('0')
				}
				while (v2.length < len) {
					v2.push('0')
				}
			
				for (let i = 0; i < len; i++) {
					const num1 = parseInt(v1[i])
					const num2 = parseInt(v2[i])
			
					if (num1 > num2) {
						return 1
					} else if (num1 < num2) {
						return -1
					}
				}
			
				return 0
			}
		}
	}
</script>

<style lang="scss" scoped>
.oper {
		display: flex;
		justify-items: center;
		margin-top: 200rpx;

		button {
			padding: 6rpx 130rpx;
		}
	}
</style>
